package nl.windgazer.arachne.services;

import nl.windgazer.arachne.pages.CaptchaImage;

import org.apache.tapestry5.Field;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.ValidationException;
import org.apache.tapestry5.ioc.MessageFormatter;
import org.apache.tapestry5.services.FormSupport;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.validator.AbstractValidator;

import com.joostschouten.common.service.catpcha.CaptchaService;



public class CaptchaValidator extends AbstractValidator<Void, Object> {
	
	private Request request;
	
	private CaptchaService _cs;

    public CaptchaValidator(Request request, CaptchaService captchaService) {
    	super(null, Object.class, "components.formelements.Captcha.validationFailed");
    	this.request = request;
    	_cs = captchaService;
    }

    public void render(Field field, Void constraintValue,
                    MessageFormatter formatter, MarkupWriter writer,
                    FormSupport formSupport) {
            formSupport.addValidation(field, "captcha", formatter.format(field.getLabel()), null);
    }

    public void validate(Field field, Void constraintValue,
                    MessageFormatter formatter, Object value) throws ValidationException {
            if (value != null) {
	            	String captchaId = (String) request.getSession(true).getAttribute(CaptchaImage.CAPTCHA_ID_KEY);
	        		boolean validated = false;
	        		if(captchaId != null) {
	        			validated = _cs.validateCaptcha(captchaId, (String)value);
	        		}
	        		if(!validated) {
	        			throw new ValidationException(formatter.format());
	        		}
            }
    }

}
